function hideForm(doc){
	var form = document.getElementById(doc);
	form.style.display = "none";
}
function showForm(doc){
	var form = document.getElementById(doc);
	form.style.display = "";
}
function showElement(doc){
	document.getElementById(doc).style.visibility = "visible";
}
function hideElement(doc){
	document.getElementById(doc).style.visibility = "hidden";
}
function setBorder(className, borderAttr){
	var inputs = document.querySelectorAll("." + className);
	for(var i=0; i<inputs.length; i++ ){
		inputs[i].style.border = borderAttr;
	}
}
function resetRegisterButton(){
	var button = document.getElementById("registerButton");
	button.onclick = toRegister;
	button.style.backgroundColor = "#ff0081";
}
function resetLoginButton(){
	var button = document.getElementById("loginButton");
	button.onclick = toLogin;
	button.style.backgroundColor = "#ff0081";
}
function toLogin(){
	showForm("loginForm");
	showElement("loginForm");
	hideElement("registerForm");
	hideElement("repeatPasswordTip");
	hideForm("registerForm");
	setBorder("input", "1px solid #f95d5d");
	document.getElementById("loginButton").style.backgroundColor = "#34d32c";
	resetRegisterButton();
	document.querySelector("#loginButton").onclick = loginSubmit;
}
function toRegister(){
	showForm("loginForm");
	showForm("registerForm");
	showElement("loginForm");
	showElement("registerForm");
	setBorder("input", "1px solid #80ff80");
	document.getElementById("registerButton").style.backgroundColor = "#34d32c";
	resetLoginButton();
	document.querySelector("#registerButton").onclick = validateCodeAuth;
}
function usernameValid(){
	var username = $("#username")[0].value;
	var usernameMatch = /\d{11}/.exec(username);
	if(usernameMatch == null || usernameMatch.length != 1){
		showElement("usernameTip");
		return false;
	}
	hideElement("usernameTip");
	return true;
}
function passwordValid(){
	var password = $("#password")[0].value;
	var passwordMatch = /\S{1,16}/.exec(password);
	if(passwordMatch == null || passwordMatch.length != 1){
		showElement("passwordTip");
		return false;
	}
	hideElement("passwordTip");
	return true;
}
function repeatPasswordValid(){
	var repeatPassword = $("#repeatPassword")[0].value;
	var password = $("#password")[0].value;
	if(!(repeatPassword == password)){
		showElement("repeatPasswordTip");
		return false;
	}
	hideElement("repeatPasswordTip");
	return true;
}
function validateCodeValid(){
	var validateCode = $('#validateCode')[0].value;
	var match = /\d{4}/.exec(validateCode);
	if(match == null || match.length != 1){
		showElement("validateCodeTip");
		return false;
	}
	hideElement("validateCodeTip");
	return true;
}
function newXmlHttp(){
	 var xmlHttp;
    try {
    	// Firefox, Opera 8.0+, Safari
    	xmlHttp = new XMLHttpRequest();
        } catch (e) {
            // Internet Explorer  
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("您的浏览器不支持AJAX！");
                return null;
            }
        }
    }
    return xmlHttp;
}
function submitAndCallback(url, formData, callback){
	var xmlHttp = newXmlHttp();
	if(xmlHttp == null){
		return;
	}
	xmlHttp.open("POST", url, true);
	setSuccessCallback(xmlHttp, callback);
	xmlHttp.send(formData);
}
function setSuccessCallback(xmlHttp, func){
	xmlHttp.onreadystatechange = function(){
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
			func(xmlHttp);
		}
	}
}
function md5With16UpperCaseChar(string){
	return $.md5(string).substring(8, 24).toUpperCase();
}
function loginSubmit(){
	if(!usernameValid()){
		 return;
	 }
	if(!passwordValid()){
		return;
	}
	var callback = function(xmlHttp){
		var result = JSON.parse(xmlHttp.responseText);
		if(result.code == 0){
			window.location.href="/main";
		}
		else{
			//登录失败
			alert("用户名或密码错误");
		}
	};
	var userType = $("#person")[0].checked ? 1 : 0;
	var formData = new FormData();
	formData.append("userType", userType);
	formData.append("userName", $("#username")[0].value);
	formData.append("password", md5With16UpperCaseChar($("#password")[0].value));
	submitAndCallback("/user/login", formData, callback);
}
function registerSubmit(){
	var callback = function(xmlHttp){
		var result = JSON.parse(xmlHttp.responseText);
		if(result.code == 0){
			loginSubmit();
			return;
		}
		else if(result.code == 11){
			alert("短信验证码错误");
		}
		else{
			//其他错误
			alert("网络繁忙，请稍后再试");
		}
	};
	var userType = $("#person")[0].checked ? 1 : 0;
	var formData = new FormData();
	formData.append("userType", userType);
	formData.append("userName", $("#username")[0].value);
	formData.append("password", md5With16UpperCaseChar($("#password")[0].value));
	submitAndCallback("/user/register", formData, callback);
}
function getValidateCode(){
	if(!usernameValid()){
		return;
	}
	var button = $('#getValidateCode')[0];
	button.disabled = "disabled";
	button.innerText = "发送成功";
	button.style.backgroundColor = "#c0c0c0";
	var countDown = function(num){
		var button = $('#getValidateCode')[0];
		if(num == 0){
			button.innerText = "获取验证码";
			button.style.backgroundColor = "#ff0081";
			button.disabled = "";
		}
		else{
			button.innerText = "等待 " + num + " 秒";
			setTimeout(function(){countDown(num - 1);}, 1000);
		}
	}
	window.setTimeout(function(){ countDown(60); }, 500);
	var username = $('#username')[0].value;
	var callback = function(xmlHttp){
		//请求获取短信验证码成功
	}
	var formData = new FormData();
	formData.append("phone", username);
	submitAndCallback("/user/authPhone", formData, callback);
}
function validateCodeAuth(){
	if(!validateCodeValid()){
		return;
	}
	if(!usernameValid()){
		 return;
	 }
	if(!passwordValid()){
		return;
	}
	if(!repeatPasswordValid()){
		return;
	}
	if(!$('#agreement')[0].checked){
		alert("您必须先同意相关协议！");
		return;
	}
	Date.prototype.Format = function (fmt) { //author: meizz 
	    var o = {
	        "M+": this.getMonth() + 1, //月份
	        "d+": this.getDate(), //日
	        "h+": this.getHours(), //小时
	        "m+": this.getMinutes(), //分
	        "s+": this.getSeconds(), //秒
	        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
	        "S": this.getMilliseconds() //毫秒
	    };
	    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	    for (var k in o)
	    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	    return fmt;
	}
	var callback = function(xmlHttp){
		registerSubmit();
	};
	var phone = $("#username")[0].value;
	var validateCode = $("#validateCode")[0].value;
	var formData = new FormData();
	formData.append("phone", phone);
	formData.append("code", validateCode);
	formData.append("fromTime", new Date().Format("yyyy-MM-dd HH:mm:ss"));
	submitAndCallback("/user/authSuccess", formData, callback);
}